package org.cable.shop.controller;


import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cable.common.constants.RedisKey;
import org.cable.common.enums.BizCodeEnum;
import org.cable.common.enums.ClientTypeEnum;
import org.cable.common.enums.ProductOrderPayTypeEnum;
import org.cable.common.interceptor.LoginInterceptor;
import org.cable.common.util.CommonUtil;
import org.cable.common.util.JsonData;
import org.cable.shop.annotation.RepeatSubmit;
import org.cable.shop.annotation.RepeatSubmit.Type;
import org.cable.shop.controller.request.ConfirmOrderRequest;
import org.cable.shop.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 二当家小D
 * @since 2021-12-25
 */
@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {


    @Autowired
    private ProductOrderService productOrderService;


    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 分页接口
     *
     * @return
     */
    @GetMapping("page")
    public JsonData page(@RequestParam(value = "page", defaultValue = "1") int page,
                         @RequestParam(value = "size", defaultValue = "10") int size,
                         @RequestParam(value = "state", required = false) String state) {

        Map<String, Object> result = productOrderService.page(page, size, state);
        return JsonData.buildSuccess(result);

    }

    /**
     * 查询订单状态接口
     *
     * @param orderTraderNo
     * @return
     */
    @GetMapping("query_state")
    public JsonData queryState(@RequestParam(value = "order_trade_no") String orderTraderNo) {
        String state = productOrderService.queryProductOrderState(orderTraderNo);
        return StringUtils.isBlank(state) ? JsonData.buildSuccess(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
    }


    @PostMapping("confirm")
    @RepeatSubmit(limitType = Type.TOKEN)
    public void confirmOrder(@RequestBody ConfirmOrderRequest orderRequest, HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(orderRequest);
        if (jsonData.getCode() == 0) {
            //终端类型
            String clientType = orderRequest.getClientType();
            //支付类型
            String payType = orderRequest.getPayType();
            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALI_PAY.name())) {

                if (clientType.equalsIgnoreCase(ClientTypeEnum.PC.name())) {
                    CommonUtil.sendHtmlMessage(response, jsonData);

                } else if (clientType.equalsIgnoreCase(ClientTypeEnum.APP.name())) {

                }

            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT_PAY.name())) {
                CommonUtil.sendJsonMessage(response, jsonData);
            }
        } else {
            log.error("创建订单失败:{}", jsonData.toString());
            CommonUtil.sendJsonMessage(response, jsonData);
        }

    }

    /**
     * 下单前获取令牌用于防重提交
     * @return
     */
    @GetMapping("token")
    public JsonData getOrderToken(){
        Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        String token = CommonUtil.getStringNumRandom(32);
        String key =String.format(RedisKey.SUBMIT_ORDER_TOKEN_KEY,accountNo,token);
        /**令牌有效期*/
        redisTemplate.opsForValue().set(key, String.valueOf(Thread.currentThread().getId()), 30, TimeUnit.MINUTES);
        return JsonData.buildSuccess(token);
    }

}

